package com.easychat.test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yudaxian
 * @Description: TODO
 * @DateTime: 2024/7/31 19:44
 **/
public class SocketServer {
    public static void main(String[] args) {
        ServerSocket server = null;
        Map<String, Socket> clientMap = new HashMap<>();
        try {
            server = new ServerSocket(1024);
            System.out.println("服务已启动，等待连接...");
            while (true) {
                Socket socket = server.accept();
                String ip = socket.getInetAddress().getHostAddress();
                System.out.println("连接成功，客户端IP：" + ip + ", 端口：" + socket.getPort());
                String clientKey = ip + ":" + socket.getPort();
                clientMap.put(clientKey, socket);

                new Thread(() -> {
                    try {
                        while (true) {
                            InputStream inputStream = socket.getInputStream();
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                            String readData = bufferedReader.readLine();
                            System.out.println("接收到客户端数据：" + readData);

                            clientMap.forEach((k, v) -> {
                                try {
                                    OutputStream outputStream = v.getOutputStream();
                                    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream));
                                    printWriter.println("服务端回复：" + socket.getPort() + "：" + readData);
                                    printWriter.flush();

                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            });

                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
